package com.xinjian.jianba.interceptor;

import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

import com.xinjian.jianba.exception.ResponseCode;
import com.xinjian.jianba.exception.ResponseCodeAwareException;

/**
 * 异常处理类.
 *
 *
 */
@ControllerAdvice
public class DefaultExceptionHandler implements HandlerExceptionResolver {

	@Override
	public ModelAndView resolveException(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex) {
		ModelAndView mv = new ModelAndView();
		String message = ResponseCode.SYSTEM_ERROR_MSG;
		Integer code = ResponseCode.ERROR;

		if (ex != null && ex instanceof ResponseCodeAwareException) {
			ResponseCodeAwareException e = (ResponseCodeAwareException) ex;
			code = e.getCode();
			message = e.getMessage();
		} else{
			code = ResponseCode.ERROR;
		}
		Map<String, Object> parametersMap = new HashMap<>();
		Enumeration<String> keysEnum = request.getParameterNames();
		if (keysEnum != null) {
			while (keysEnum.hasMoreElements()) {
				String key = keysEnum.nextElement();
				String value = request.getParameter(key);
				parametersMap.put(key, value);
			}
		}
		Map<String, Object> result = new HashMap<String, Object>();
		result.put("code", code + "");
		result.put("message", message);
		result.put("result", null);
		MappingJackson2JsonView view = new MappingJackson2JsonView();
		view.setAttributesMap(result);
		mv.setView(view);
		return mv;
	}
}
